//
//  BWOAuthViewController.swift
//  weibo
//
//  Created by libowen on 16/5/22.
//  Copyright © 2016年 libowen. All rights reserved.
//

import UIKit
import SVProgressHUD

class BWOAuthViewController: UIViewController {
    let webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
    }
        
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBar()
        loadOauthPage()
    }
    
    private func loadOauthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
   
}
extension BWOAuthViewController {
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func textAccount() {
        let jsString = "document.getElementById('userId').value = '18501164825', document.getElementById('passwd').value = '199357libowen' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试数据", target: self, action: "textAccount")
    }
}
extension BWOAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView:UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString ?? ""
        let successFlag = "code="
        if urlString.containsString(successFlag) {

            let range = urlString.rangeOfString(successFlag)!
            let code = urlString.substringFromIndex(range.endIndex)
//            loadAccessToken(code)
            BWUserAccountModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                if !isSuccess {
                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                }
//                SVProgressHUD.showSuccessWithStatus("授权成功~~")
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
            })
            return false
        }
        return true
    }
    
    
    
    
}























